package screen;

import java.util.Hashtable;

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldConfig;
import net.rim.device.api.browser.field2.BrowserFieldListener;
import net.rim.device.api.script.ScriptEngine;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

import org.w3c.dom.Document;

import code.Function;
import code.StringUtility;
import code.WeiboConfig;
import ctrl.MyConnectionFactory;

public class WeiboAuthorizeScreen extends MainScreen
{
	public Hashtable _access_token=new Hashtable();
	private BrowserFieldListener listener;

	public WeiboAuthorizeScreen(String url) 
	{
		super(FOCUSABLE | VERTICAL_SCROLL | VERTICAL_SCROLLBAR | NO_SYSTEM_MENU_ITEMS);

		MyConnectionFactory factory=new MyConnectionFactory();
		BrowserFieldConfig config=new BrowserFieldConfig();
		config.setProperty(BrowserFieldConfig.CONNECTION_FACTORY, factory);
		
		BrowserField bf=new BrowserField(config);
		listener=new BrowserFieldListener()
		{
			public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) throws Exception 
			{
				if(browserField.getDocumentUrl().startsWith(WeiboConfig.redirect_URI))
				{
					handleRedirectUrlCode(browserField.getDocumentUrl());
					onClose();
					return;
				}

				super.documentCreated(browserField, scriptEngine, document);
			}
		};
		
		add(bf);
		
		bf.addListener(listener);
		bf.requestContent(url+Function.updateConnectionSuffix());
	}

	private void handleRedirectUrlCode(String url)
	{
		Hashtable values = StringUtility.decodeUrlCode(url);

		String error = (String) values.get("error");
		String error_code = (String) values.get("error_code");

		if (error == null && error_code == null) {
			_access_token = values;
		} else {
			if (error_code == null) {
				Dialog.alert("error: " + error);
			} else {
				Dialog.alert("error: " + error_code);
			}
		}
	}
	
	public Hashtable getAccessToken()
	{
		return _access_token;
	}
	
	protected boolean onSavePrompt() {return true;}
}